package com.yfyszk.kingbird.controller;


import com.yfyszk.kingbird.common.result.ApiResult;
import com.yfyszk.kingbird.common.utils.DateUtils;
import com.yfyszk.kingbird.common.utils.IdWorkerUtils;
import com.yfyszk.kingbird.common.vo.UploadFileVO;
import com.yfyszk.kingbird.upload.MinioService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 文件上传接口
 *
 *
 * @description:
 * @author: wgc
 * @contact:
 * @date: 2020年08月06日 下午3:03:17
 * @version V1.0
 * @Copyright  北京金雀互联信息技术有限公司。
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(value = "/upload")
@Slf4j
public class UploadController {
    @Autowired
    private MinioService minioService;


    @RequestMapping(value = "/uploadFile")
    public Object uploadFile(HttpServletRequest request, HttpServletResponse response) {
        try {
            String bucket = DateUtils.nowDayTimeStamp();
            minioService.makeBucket(bucket);
            minioService.setBucketPolicy(bucket,"read-write");
            // 单个文件上传
            String objectKey = IdWorkerUtils.getInstance().nextId() + "";
            UploadFileVO uploadFileVO =  minioService.uploadInputStreamForThumbForWebOrApp(bucket,objectKey,request);
            if (uploadFileVO != null) {
                // 每次上传成功将信息返回给前端
                log.info("----------返回文件成功---------{}",uploadFileVO);
                return ApiResult.success( "上传成功", uploadFileVO);
            } else {
                return ApiResult.error("上传失败");
            }


        } catch (Exception e) {
            log.error("文件上传失败:{}",e.getMessage());
            return ApiResult.error("上传失败");
        }
    }



}
